package zjc.bookkeeping.fragment.statistics;

import android.graphics.Color;
import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dld.view.SegmentedControlItem;
import com.dld.view.SegmentedControlView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.data.RadarDataSet;
import com.github.mikephil.charting.data.RadarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.android.material.tabs.TabLayout;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import zjc.bookkeeping.R;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.fragment.tools.MyMarkerView;
import zjc.bookkeeping.fragment.tools.MyPercentFormatter;
import zjc.bookkeeping.fragment.tools.XYMarkerView;
import zjc.bookkeeping.tools.RadarMarkerView;


public class StatisticsYearFragment extends Fragment {
    private View fragment_statistics_year;
    private TabLayout tabLayout;
    private SegmentedControlView mscv;//收支统计柱形图-收支结余转换
    private BarChart chart;// 柱形图
   // private RadarChart chart2;//雷达图
    private PieChart chart4; //饼状图
    private LineChart chart3;//折线图
    private TextView year_expend;
    private TextView year_income;
    private TextView year_balance;
    private CardView cardview1;
    private CardView cardview4;
    private CardView cardview2;
    private CardView cardview5;
    private float[][] months_money = new float[3][];
    private List<String> consumptionClasses = new ArrayList<>();//消费分类
    private int width;
    private int height;

    DecimalFormat df = new DecimalFormat("#0.00");// 保留两位小数





    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragment_statistics_year = inflater.inflate(R.layout.fragment_statistics_year,container,false);
        //获取屏幕宽度
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;
        initView();
        Adaptation();
        return fragment_statistics_year;
    }

    public void Adaptation(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.width = (int) (width * 0.9);
        layoutParams.height = (int) (width * 0.9 * 0.25);
        //Log.e("height2", String.valueOf(layoutParams.height));
        layoutParams.topMargin = (int) (width * 0.05);
        layoutParams.leftMargin = (int) (width * 0.05);
        layoutParams.rightMargin = (int) (width * 0.05);
        cardview1.setLayoutParams(layoutParams);

        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams2.height = (int) (width * 0.9 * 0.618);
        layoutParams2.width = (int) (width * 0.9);
        layoutParams2.topMargin = (int) (width * 0.05);
        layoutParams2.leftMargin = (int) (width * 0.05);
        layoutParams2.rightMargin = (int) (width * 0.05);
        cardview4.setLayoutParams(layoutParams2);
        cardview2.setLayoutParams(layoutParams2);

        LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams3.width = (int) (width * 0.9);
        layoutParams3.height = (int) (width * 0.9 * 0.718);
        layoutParams3.topMargin = (int) (width * 0.05);
        layoutParams3.leftMargin = (int) (width * 0.05);
        layoutParams3.rightMargin = (int) (width * 0.05);
        layoutParams3.bottomMargin = (int) (width * 0.08);
        cardview5.setLayoutParams(layoutParams3);

    }
    public void initView(){
        cardview1 = fragment_statistics_year.findViewById(R.id.cardview1);
        cardview2 = fragment_statistics_year.findViewById(R.id.cardview2);
        cardview4 = fragment_statistics_year.findViewById(R.id.cardview4);
        cardview5 = fragment_statistics_year.findViewById(R.id.cardview5);
        tabLayout = fragment_statistics_year.findViewById(R.id.tab_layout);
        mscv = fragment_statistics_year.findViewById(R.id.scv);
        chart = fragment_statistics_year.findViewById(R.id.chart1);
        //chart2 = fragment_statistics_year.findViewById(R.id.chart2);
        year_income = fragment_statistics_year.findViewById(R.id.year_income);
        year_expend = fragment_statistics_year.findViewById(R.id.year_expend);
        year_balance = fragment_statistics_year.findViewById(R.id.year_balance);
        chart3 = fragment_statistics_year.findViewById(R.id.linechart);
        chart4 = fragment_statistics_year.findViewById(R.id.chart3);
        // 年份选择
        Calendar date = Calendar.getInstance();
        int currentYear = date.get(Calendar.YEAR);
        float expend = DBManager.getYearSumConsumption(currentYear, 0);
        float income = DBManager.getYearSumConsumption(currentYear,1);
        float balance = income - expend;
        year_expend.setText(df.format(expend));
        year_income.setText(df.format(income));
        year_balance.setText(df.format(balance));

        for (int i = currentYear; i >= 2000; i--) {
            tabLayout.addTab(tabLayout.newTab().setText(String.valueOf(i)+"年"));
        }
        // 收支统计柱形图
        StatisticsData(currentYear);
        chart(0);
        //radarChart(currentYear);//雷达图
        lineChart(currentYear);
        pieChart(currentYear);

        // 分段选择器
        List<SegmentedControlItem> items = selectItems();
        mscv.addItems(items);
        mscv.setSelectedItem(0);
        mscv.setOnSegItemClickListener(new SegmentedControlView.OnSegItemClickListener() {
            @Override
            public void onItemClick(SegmentedControlItem item, int position) {
                //String msg = String.format(Locale.getDefault(), "click scv2 selected:%d", position);
               // Log.d("分段选择", msg);
                String str = (String) tabLayout.getTabAt(tabLayout.getSelectedTabPosition()).getText();
                int year = Integer.parseInt(str.substring(0,4));
                chart(position);
                chart.highlightValue(null);
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String str = (String) tabLayout.getTabAt(tabLayout.getSelectedTabPosition()).getText();
                int year = Integer.parseInt(str.substring(0,4));
                float expend = DBManager.getYearSumConsumption(year, 0);
                float income = DBManager.getYearSumConsumption(year,1);
                float balance = income - expend;
                year_expend.setText(String.valueOf(expend));
                year_income.setText(String.valueOf(income));
                year_balance.setText(String.valueOf(balance));
                StatisticsData(year);
                chart(mscv.getSelectedItem());
                //radarChart(year);
                lineChart(year);
                chart3.highlightValue(null);
                chart4.highlightValue(null);
                chart.highlightValue(null);
                pieChart(year);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void pieChart(int year){
        chart4.setUsePercentValues(true);
        chart4.getDescription().setEnabled(false);
        chart4.setExtraOffsets(5, 10, 5, 5);

        chart4.setDragDecelerationFrictionCoef(0.95f);

        chart4.setDrawHoleEnabled(true);
        chart4.setHoleColor(Color.WHITE);

        chart4.setTransparentCircleColor(Color.WHITE);
        chart4.setTransparentCircleAlpha(110);

        chart4.setHoleRadius(58f);
        chart4.setTransparentCircleRadius(61f);

        chart4.setDrawCenterText(true);

        chart4.setRotationAngle(0);
        chart4.setRotationEnabled(true);
        chart4.setHighlightPerTapEnabled(true);

        chart4.animateY(1400, Easing.EaseInOutQuad);

        Legend l = chart4.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);

        chart4.setEntryLabelColor(Color.parseColor("#ff999999"));

        chart4.setEntryLabelTextSize(0f);


        ArrayList<PieEntry> entries = new ArrayList<>();

        consumptionClasses = DBManager.getAllConsumptionClass();
        int length = consumptionClasses.size();
        ArrayList<String> class_name = new ArrayList<>();
        ArrayList<Float> class_money = new ArrayList<>();
        for (int i = 0; i < length; i ++){
            float temp = DBManager.getYearClassConsumption(year,consumptionClasses.get(i));
            if (temp != 0){
                Log.e("classname",consumptionClasses.get(i));
                class_name.add(consumptionClasses.get(i));
                class_money.add(temp);
            }
        }
        int length2 = class_name.size();
        final String[] parties = new String[length2];
        for (int i = 0; i < length2; i ++){
            Log.i("消费分类",consumptionClasses.get(i));
            parties[i] = class_name.get(i);
            entries.add(new PieEntry((float) (class_money.get(i)),
                    parties[i % parties.length]));
        }



        PieDataSet dataSet = new PieDataSet(entries, "");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(Color.parseColor("#ff999999"));

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new MyPercentFormatter(chart4));
        data.setValueTextSize(8f);
        data.setValueTextColor(Color.parseColor("#ff999999"));
        // data.setValueTypeface(tfLight);


        chart4.setData(data);
        if (length2 == 0){
            Log.e("data","null");
            chart4.setCenterText("暂无数据");
        }else {
            chart4.setCenterText("总消费" + "\n" + year_expend.getText());
        }
        chart4.setNoDataText("暂无数据");
        // undo all highlights
        chart4.highlightValues(null);

        chart4.setCenterTextColor(Color.parseColor("#ff999999"));


        chart4.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                PieEntry p = (PieEntry) e;
                Log.e("entry", p.getLabel());
                chart4.setCenterText(p.getLabel() + "\n" + e.getY());
            }

            @Override
            public void onNothingSelected() {
                chart4.setCenterText("总消费" + "\n" + year_expend.getText());
            }
        });

        chart4.invalidate();

    }

    public void lineChart(int year){
        chart3.getDescription().setEnabled(false);
        chart3.setTouchEnabled(true);
        chart3.setDragDecelerationFrictionCoef(0.9f);
        chart3.setDragEnabled(true);
        chart3.setScaleEnabled(true);
        chart3.setDrawGridBackground(false);
        chart3.setHighlightPerDragEnabled(true);
        chart3.setVisibleXRangeMinimum(1);

        chart3.setPinchZoom(true);
        chart3.animateX(0);

        Legend l = chart3.getLegend();//图例
        l.setForm(Legend.LegendForm.LINE);
        l.setTextSize(10f);
        l.setTextColor(Color.GRAY);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        XAxis xAxis = chart3.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularityEnabled(true);
        xAxis.setGranularity(1);
        xAxis.setSpaceMax(1f);

        xAxis.setTextSize(10f);//x轴字体大小
        xAxis.setTextColor(Color.GRAY);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        //      xAxis.setAxisMinimum(-20f);


        YAxis leftAxis = chart3.getAxisLeft();
        leftAxis.setTextColor(Color.GRAY);
        //leftAxis.setAxisMaximum(200f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
        //leftAxis.setGranularity(1);
        leftAxis.setDrawAxisLine(false);//隐藏y轴左侧轴线

        YAxis rightAxis = chart3.getAxisRight();
        rightAxis.setEnabled(false); // 隐藏右侧y轴

        String[] xLabels = new String[12];
        xAxis.setLabelCount(12);

        for (int i = 1; i <= 12; i++){
            xLabels[i-1] = String.valueOf(i);
        }
        xAxis.setValueFormatter(new ValueFormatter() {   //X轴自定义标签内容
            @Override
            // index从1开始 作为数组下标-1
            public String getAxisLabel(float index, AxisBase axisBase) {
                Log.i("下标1",String.valueOf(index));
                if (index < 13) {
                    Log.i("下标2",String.valueOf((int) index % xLabels.length));
                    return xLabels[(int) (index-1)];
                } else {
                    return "";
                }
//
//                //Log.i("下标",String.valueOf(index));
//                Log.i("index",String.valueOf(index));
//                if (index < 0 || index >= xLabels.length) {
//                    return "";
//                }
//                return xLabels[(int)(index-1)];
            }
        });



        LineDataSet set;
        LineData data = new LineData();
        ArrayList<Entry> values = new ArrayList<Entry>();

        for (int j = 1; j <= 12; j ++){
            values.add(new Entry(j, months_money[0][j-1]));;
        }
        set = new LineDataSet(values,null);
        set.setForm(Legend.LegendForm.NONE);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(Color.parseColor("#7CB2EB"));
        set.setCircleColor(Color.BLUE);
        set.setLineWidth(1f);
        set.setCircleRadius(3f);
        set.setFillAlpha(65);
        set.setFillColor(Color.BLUE);
        set.setHighLightColor(Color.BLUE);
        set.setDrawCircleHole(false);
        set.setDrawCircles(false);
        set.setDrawValues(false);//隐藏折线点上的数据
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        data.addDataSet(set);
        set.setHighLightColor(Color.TRANSPARENT);

        data.setValueTextColor(Color.GRAY);
        data.setValueTextSize(9f);


        chart3.setData(data);
        MyMarkerView mv = new MyMarkerView(getContext(), R.layout.custom_marker_view,String.valueOf(year));
        // Set the marker to the chart
        mv.setChartView(chart3);
        chart3.setMarker(mv);
    }





    private List<SegmentedControlItem> selectItems(){
        List<SegmentedControlItem> items = new ArrayList<>();
        items.add(new SegmentedControlItem(getResources().getString(R.string.expenses)));
        items.add(new SegmentedControlItem(getResources().getString(R.string.income)));
        items.add(new SegmentedControlItem(getResources().getString(R.string.balance)));
        return items;
    }

    private void chart(int kind){
        chart.removeAllViews();
        chart.getAxisLeft().setEnabled(true);
       // chart.getAxisLeft().setAxisMinimum(0f);
        chart.getAxisRight().setEnabled(false);//隐藏y轴右侧
        chart.getAxisLeft().setDrawAxisLine(false);// 隐藏左侧轴线
        //chart.getAxisLeft().setDrawGridLines(false);
        chart.getAxisLeft().setDrawGridLines(true);
        chart.getAxisLeft().setGranularityEnabled(true);
        chart.getXAxis().setEnabled(true);
        chart.getXAxis().setDrawAxisLine(false);
        chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);//x轴位置

        chart.setDrawBarShadow(false);//隐藏阴影
        chart.setDrawValueAboveBar(true);

        chart.getXAxis().setDrawGridLines(false);//去掉柱状图背后的竖线

        chart.getDescription().setEnabled(false);//禁用描述
        chart.getLegend().setEnabled(false);//禁用图例

        chart.setPinchZoom(false);

        chart.setDrawGridBackground(false);


        ArrayList<BarEntry> values = new ArrayList<>();



        for (int i = 1; i <= 12; i++) {
            values.add(new BarEntry(i,months_money[kind][i-1]));
            //float val = DBManager.getMonthComsumption(year,i,kind);
//            float val = (float) (Math.random() * (100 + 1));
//
//            if (Math.random() * 100 < 25) {
//                values.add(new BarEntry(i, val));
//            } else {
//                values.add(new BarEntry(i, val));
//            }
        }


        XAxis xAxis = chart.getXAxis();
        xAxis.setTextSize(10f);//x轴字体大小
        //xAxis.setAxisMinimum(1);
        // xAxis.setAxisMaximum(30);
        xAxis.setLabelCount(12);





        BarDataSet dataSets = new BarDataSet(values,"");
        dataSets.setColor(Color.parseColor("#5E80BF"));//改变柱形图颜色
        dataSets.setHighLightColor(Color.parseColor("#13227a"));

        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);//数据字体大小
        data.setBarWidth(0.3f);
        data.setDrawValues(false);

        chart.setData(data);
        XYMarkerView mv = new XYMarkerView(getContext());
        mv.setChartView(chart); // For bounds control
        chart.setMarker(mv);
    }

    private void StatisticsData(int year){
        months_money[0] = new float[12];
        months_money[1] = new float[12];
        months_money[2] = new float[12];
        for (int i = 0; i < 12; i++) {
            float val0 = DBManager.getMonthConsumption(year,i+1,0);
            float val1 = DBManager.getMonthConsumption(year,i+1,1);
            float val2 = val1 - val0;
            months_money[0][i] = val0;
            months_money[1][i] = val1;
            months_money[2][i] = val2;
        }
    }

}